/*
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2022-03-22 12:12:49
 * @LastEditTime: 2023-04-06 17:58:25
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: HTTP拦截器
 * @FilePath: \vue3-element-plus-web\src\utils\request.js
 * @Copyright 版权声明
 */
import axios from 'axios'
// import { MessageBox } from 'element-plus'
import store from '../store'
import { getToken } from '@/utils/auth'
import { DonMessage } from '@/utils/DonMessage'
import { HTTP_API_CRYPTO/*, HTTP_API_PASS_FILE_ENUM*/ } from '@/config'
// import qs from 'qs'

// console.log('--HTTP_API_CRYPTO--', HTTP_API_CRYPTO)
// console.log('--HTTP_API_PASS_FILE_ENUM--', HTTP_API_PASS_FILE_ENUM)

// 当前请求的接口是否需要加解密
let httpApiCryptoHandle = false

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_URL, // api的base_url
  withCredentials: false, // 携带cookie
  timeout: 50000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    // console.log('--request config--', config)
    // config.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
    if (typeof config.headers['No-Token'] === 'undefined' || config.headers['No-Token'] === false) {
      if (store.getters.token) {
        config.headers['Auth'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      }
    }

    // if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
    //   config.data = qs.stringify(config.data)
    // }

    // 判断系统配置 HTTP_API_CRYPTO 的值，如果为 true 即对入参进行加密
    if (HTTP_API_CRYPTO === true) {
      // 判断当前调用的接口 headers 中的 API-CRYPTO 值， true： 加密 false： 不加密
      if (typeof config.headers['API-CRYPTO'] !== 'undefined' && config.headers['API-CRYPTO'] === false) {
        httpApiCryptoHandle = false
      } else {
        httpApiCryptoHandle = true
      }
    } else {
      httpApiCryptoHandle = false
    }

    // 入参需要 加密
    if (httpApiCryptoHandle === true) {
      // console.log('--httpApiCryptoHandle--', httpApiCryptoHandle)
    }

    return config
  },
  (error) => {
    // Do something with request error
    // console.log(error) // for debug
    Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  (response) => {
    // console.log('--response--', response)
    let responseAll = false
    if (typeof response.config.headers['Response-All'] !== 'undefined' && response.config.headers['Response-All'] === true) {
      responseAll = true
    }
    // 出参需要 解密
    if (httpApiCryptoHandle === true) {
      // console.log('--response httpApiCryptoHandle--', httpApiCryptoHandle)
    }

    /**
     * code 可结合自己业务进行修改
     */
    const res = response.data
    if (typeof res.code === 'undefined') {
      return Promise.resolve((responseAll === true) ? response : res)
    }
    if (res.code !== 200) {
      if (typeof response.config.headers['Error-Echo'] === 'undefined' || response.config.headers['Error-Echo'] === true) {
        new DonMessage().error({
          message: res.msg || '系统异常',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject((responseAll === true) ? response : res)
    } else {
      return Promise.resolve((responseAll === true) ? response : res)
    }
  },
  (error) => {
    console.log(`🚀 ~ file: request.js ~ line 104 ~ error`, error)
    if (typeof error.config.headers['Error-Echo'] === 'undefined' || error.config.headers['Error-Echo'] === true) {
      // 401 、 403 使用 HTTP code
      const response = error.response
      if (typeof response === 'undefined') {
        new DonMessage().error({
          message: '网络异常，请联系管理员！',
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        const { status } = response
        // console.log('err' + error)// for debug
        // console.log('error.response', response)
        // console.log('status', status)
        // 401:未登录/token失效; 403:未授权; 405:方法禁止访问
        switch (status) {
          case 401:
            new DonMessage().error({
              message: '登录超时，请重新登录！',
              type: 'error',
              duration: 5 * 1000
            })
            store.dispatch('FedLogOut').then(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
            break
          case 403:
            new DonMessage().error({
              message: '您未授权访问此功能，请联系管理员！',
              type: 'error',
              duration: 5 * 1000
            })
            break
          case 405:
            new DonMessage().error({
              message: error.msg,
              type: 'error',
              duration: 5 * 1000
            })
            break
          default:
            new DonMessage().error({
              message: error.msg || '系统异常',
              type: 'error',
              duration: 5 * 1000
            })
        }
      }
    }
    return Promise.reject(error)
    // console.log('err' + error) // for debug
    // if (error.indexOf('cancelToken') > -1) {
    //   new DonMessage().error({
    //     message: error.msg,
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    // }
    // return Promise.reject(error)
  }
)

export default service
